from django.shortcuts import render_to_response
from django.template import RequestContext
from django.contrib.auth import login,logout,authenticate
from django.http import HttpResponseRedirect
from huellas.apps.home.forms import LoginForm, lista_personas, lista_ventas
from huellas.apps.principal.models import Clientes, Ventas

def index_view (request):
	return render_to_response('home/index.html', context_instance=RequestContext(request))

def ventas_view (request):
	return render_to_response('home/ventas.html', context_instance=RequestContext(request))

def personas_view (request):
	return render_to_response('home/personas.html', context_instance=RequestContext(request))

def login_view(request):
	mensaje = ""
	if request.user.is_authenticated():
		return HttpResponseRedirect('/')
	else:
		if request.method == "POST":
			form = LoginForm(request.POST)
			if form.is_valid():
				username = form.cleaned_data['username']
				password = form.cleaned_data['password']
				usuario = authenticate(username=username,password=password)
				if usuario is not None and usuario.is_active:
					login(request,usuario)
					return HttpResponseRedirect('/')
				else:
					mensaje = "usuario y/o password incorrecto"
		form = LoginForm()
		ctx = {'form':form,'mensaje':mensaje}
		return render_to_response('home/login.html',ctx,context_instance=RequestContext(request))

def logout_view(request):
	logout(request)
	return HttpResponseRedirect('/')

def personas_view(request):
	mensaje = ""
	if request.user.is_authenticated():
		if request.method=="POST":
			form = lista_personas(request.POST)
		
			if form.is_valid():
				documento=form.cleaned_data['documento']
				per= Clientes.objects.filter(codigo_cliente=documento)
				form = lista_personas()
				ctx= {'form':form,'personas':per}
				return render_to_response('home/personas.html',ctx,context_instance=RequestContext(request))
			else:
				mensaje = "Documento no es valido"
		form = lista_personas()
		ctx = {'form':form, 'mensaje':mensaje}	
		return render_to_response('home/personas.html',ctx,context_instance=RequestContext(request))

	else:
		return HttpResponseRedirect('/')


def ventas_view(request):
	mensaje = ""
	if request.user.is_authenticated():
		if request.method=="POST":
			form = lista_ventas(request.POST)
		
			if form.is_valid():
				factura=form.cleaned_data['factura']
				fact=Ventas.objects.filter(codigo_venta=factura)
				form = lista_ventas()
				ctx= {'form':form,'facturas':fact}
				return render_to_response('home/ventas.html',ctx,context_instance=RequestContext(request))
			else:
				mensaje = "El nombre No Existe"
		form = lista_ventas()
		ctx = {'form':form, 'mensaje':mensaje}	
		return render_to_response('home/ventas.html',ctx,context_instance=RequestContext(request))
	else:
		return HttpResponseRedirect('/')